package boardgamer.yavalath.client.threads;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
import boardgamer.common.client.AbstractView;

import static com.google.common.base.Preconditions.checkNotNull;

public class UiThread implements Runnable {

  private final AbstractView<?> view;
  private final SurfaceHolder surfaceHolder;
  private final GameThread gameThread;

  public UiThread(AbstractView<?> view, GameThread gameThread) {
    this.view = checkNotNull(view, "view");
    this.surfaceHolder = checkNotNull(view.getHolder(), "surfaceHolder");
    this.gameThread = checkNotNull(gameThread, "gameThread");
  }

  @Override
  public void run() {
    while (!Thread.interrupted()) {
      Canvas canvas = null;
      try {
        switch (gameThread.getGameState()) {
          case STATE_RUN:
            synchronized (surfaceHolder) {
              canvas = surfaceHolder.lockCanvas(null);
              if (canvas == null) {
                Thread.sleep(100);
              } else {
                view.draw(canvas);
              }
            }
            break;
          case STATE_PAUSE:
            Thread.sleep(100);
            break;
          default:
            break;
        }
      } catch (Exception e) {
        Log.e("GameThread(e)", view.getClass() + Log.getStackTraceString(e));
      } finally {
        if (canvas != null) {
          surfaceHolder.unlockCanvasAndPost(canvas);
        }
      }
    }
  }
}
